<?php 
	class MysqlSession {
		public $db;
		private $table = "php_session";
		public $max_life_time;
		
		public function MysqlSession($db=null){
			$this->max_life_time = get_cfg_var("session.gc_maxlifetime");
			if(empty($db)){
				$this->db = new mydb();
			}else{
				$this->db = $db;
			}
		}
		
		public function open($save_path, $session_name){
			return true;
		}
		
		public function close(){
			$this->db = null;
			return true;
		}
		
		public function read($sid){
			$sql = "SELECT `value` FROM `{$this->table}` WHERE `sid`='".$this->db->escape($sid)."' and `expiry` > ".time()." LIMIT 1";
			$value = $this->db->get_var($sql);
			return $value;
		}
		
		public function write($sid, $value){
			$expiry = time()+$this->max_life_time;
			$sql = "REPLACE INTO `{$this->table}`(`sid`,`expiry`,`value`) VALUES('".$this->db->escape($sid)."',".$expiry.",'".$this->db->escape($value)."')";
			return $this->db->query($sql);
		}
		
		public function destroy($sid){
			$sql = "DELETE FROM `{$this->table}` WHERE `sid`='".$this->db->escape($sid)."'";
			return $this->db->query($sql);
		}
		
		public function gc($max_life_time){
			$sql = "DELETE FROM `{$this->table}` WHERE `expiry`<".time();
			return $this->db->query($sql);
		}
	}
	
	/*$mySession = new MysqlSession();
	session_module_name('user');
	session_set_save_handler(
		array(&$mySession, 'open'),
		array(&$mySession, 'close'),
		array(&$mySession, 'read'),
		array(&$mySession, 'write'),
		array(&$mySession, 'destroy'),
		array(&$mySession, 'gc')
	);*/
	session_start();